package diagnostics

import (
	"net/http"
	_ "net/http/pprof"

	log "github.com/sirupsen/logrus"

	"github.com/google/gops/agent"
)

type DiagnosticsConfig struct {
	PprofHttpListenAddr string `mapstructure:"pprof_http_listen_addr"`
}

func StartDiagnosticTool(c *DiagnosticsConfig) error {
	startGopsAgent()
	startPprofHttpServer(c.PprofHttpListenAddr)
	return nil

}

func startGopsAgent() error {
	if err := agent.Listen(agent.Options{}); err != nil {
		log.Fatal("gops agent failed to start")
	}

	return nil
}

func startPprofHttpServer(addr string) error {
	go func() {
		err := http.ListenAndServe(addr, nil)
		if err != nil {
			log.Errorf("failed to start diagnostics http server, err=%s", err.Error())
		}
	}()

	return nil
}
